package top.vanchor.flexible.utils;

import cn.hutool.core.util.IdcardUtil;
import lombok.Data;
import top.vanchor.flexible.entity.model.DateRange;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class DateUtils {
    public static Integer getAge(String idCard) {
        IdcardUtil.Idcard info = IdcardUtil.getIdcardInfo(idCard);
        return info.getAge();
    }

    public static int calculateMonthDifference(Date startDate, Date endDate) {
        // 转换为 LocalDate
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 确保 startDate 在 endDate 之前
        if (startLocalDate.isAfter(endLocalDate)) {
            LocalDate temp = startLocalDate;
            startLocalDate = endLocalDate;
            endLocalDate = temp;
        }

        // 计算月差
        int months = (int) ChronoUnit.MONTHS.between(startLocalDate.withDayOfMonth(1), endLocalDate.withDayOfMonth(1));

        // 检查是否跨越了月份
        if (endLocalDate.getDayOfMonth() > startLocalDate.getDayOfMonth()) {
            months++;
        }

        return months;
    }

    /**
     * 拆分月数
     * @param beginTime 开始日期
     * @param endTime 结束日期
     * @return 按月拆分后的结果
     */
    public static List<DateRange> splitMonths(Date beginTime, Date endTime) {
        List<DateRange> dateRangeList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        // 设置开始日期
        calendar.setTime(beginTime);
        while (calendar.getTime().before(endTime) || calendar.getTime().equals(endTime)) {
            Date startOfMonth = calendar.getTime();
            // 计算结束日期
            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            Date endOfMonth = calendar.getTime();
            dateRangeList.add(new DateRange(startOfMonth, endOfMonth));
            // 前进一个月
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1); // 设置为下月的第一天
        }
        return dateRangeList;
    }

    /**
     * 传递日期类型，返回格式化的String类型
     * @param date 日期
     * @param format 格式化目标
     * @return 格式化值
     */
    public static String dateFormat(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }

    /**
     * 获取当前日期在当前月份的第1天
     * @param date 日期
     * @return 当月第一天
     */
    public static Date getFirstDayOfMonth(Date date) {
        Calendar firstTimeCal = Calendar.getInstance();
        firstTimeCal.setTime(date);
        firstTimeCal.set(Calendar.DAY_OF_MONTH, 1);
        return firstTimeCal.getTime();
    }

    /**
     * 获取当前日期在当前月份的最后1天
     * @param date 日期
     * @return 当月最后一天
     */
    public static Date getLastDayOfMonth(Date date) {
        Calendar nowCal = Calendar.getInstance();
        nowCal.setTime(date);
        nowCal.set(Calendar.DAY_OF_MONTH, nowCal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return nowCal.getTime();
    }

    /**
     * 计算某一日期的N年前（忽略日）
     * @param compareDate 目标日期，如2024-07-15
     * @param year 回溯年份，如5
     * @return 某一月的第一天，如2019-08-01
     */
    public static Date getDateBeforeYear(Date compareDate, int year) {
        int compareYear = Integer.parseInt(DateUtils.dateFormat(compareDate, "yyyy"));
        int compareMonth = Integer.parseInt(DateUtils.dateFormat(compareDate, "MM"));
        //计算五年前应该是什么样的
        int targetYear = compareYear - year;
        int targetMonth = compareMonth + 1;
        if (targetMonth > 12) {
            targetMonth = 1;
            targetYear++;
        }
        String targetMonthStr = targetMonth >= 10 ? targetMonth + "" : "0" + targetMonth;
        String targetDateStr = targetYear + "-" + targetMonthStr+"-01";
        //处理为Date类型
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(targetDateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }


    public static int compareDateForDay(Date date1, Date date2) {
        LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 比较两个 LocalDate 对象（只比较日期部分）
        if (localDate1.isBefore(localDate2)) {
            return -1;
        } else if (localDate1.isAfter(localDate2)) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 将所需年份转化为12个月每个月的始末时间
     * @param year 年份
     * @return 二维数组
     */
    public static Date[][] getYearDateRanges(int year) {
        Date[][] dateRanges = new Date[12][2];

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));

        for (int month = 0; month < 12; month++) {
            calendar.set(year, month, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date startDate = calendar.getTime();

            calendar.set(year, month, calendar.getActualMaximum(Calendar.DAY_OF_MONTH), 23, 59, 59);
            calendar.set(Calendar.MILLISECOND, 999);
            Date endDate = calendar.getTime();

            dateRanges[month][0] = startDate;
            dateRanges[month][1] = endDate;
        }

        return dateRanges;
    }
}
